package com.example.video.ui;

import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.CursorAdapter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.video.Config;
import com.example.video.R;
import com.example.video.io.database.TBL_App;
import com.example.video.io.database.TBL_Content;
import com.google.android.youtube.player.YouTubeStandalonePlayer;
import com.viewpagerindicator.TabPageIndicator;

public class MainActivity extends FragmentActivity{
	public static final int PAGE_VIDEO=0;
	public static final int PAGE_VIDEO_HISTORY=PAGE_VIDEO+1;
	public static final int PAGE_APP=PAGE_VIDEO_HISTORY+1;
	
	private static final int REQ_START_STANDALONE_PLAYER = 1;
	private static final int REQ_RESOLVE_SERVICE_MISSING = 2;
	
	private ViewPager mViewPager;
	private TabPageIndicator mTabPageIndicator;
	private MyViewPagerAdapter viewPagerAdapter;
	private OnVideoItemClickListener mVideoItemClickListener;
	private OnAppItemClickListener mOnAppItemClickListener;
	
	private static String[] TABS;
	
	public static interface OnVideoItemClickListener {
		public void onVideoItemClick(String videoID);
	}
	public interface OnAppItemClickListener{
		public void onAppItemClick(String url);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}
	
	private void initView(){
		mViewPager=(ViewPager)findViewById(R.id.activity_main_pager);
		mTabPageIndicator=(TabPageIndicator)findViewById(R.id.activity_main_indicator);
		TABS=getResources().getStringArray(R.array.tabs);
		
		mVideoItemClickListener=new OnVideoItemClickListener() {
			
			@Override
			public void onVideoItemClick(String videoID) {
//				startVideo(videoID);
//				tickWatched(videoID);
//				Toast.makeText(getApplicationContext(), videoID, Toast.LENGTH_LONG).show();
			}
		};
		
		mOnAppItemClickListener=new OnAppItemClickListener() {
			
			@Override
			public void onAppItemClick(String url) {
				Toast.makeText(getApplicationContext(), url, Toast.LENGTH_LONG).show();
			}
		};
		viewPagerAdapter=new MyViewPagerAdapter(getSupportFragmentManager(),mVideoItemClickListener,mOnAppItemClickListener);
		mViewPager.setAdapter(viewPagerAdapter);
		mTabPageIndicator.setViewPager(mViewPager);
	}
	
	private void tickWatched(String videoID){
		String selection=TBL_Content.VIDEO_ID+"=?";
		String[] selectionArgs=new String[]{videoID};
		ContentValues values=new ContentValues();
		values.put(TBL_Content.IS_WATCH, 1);
		getContentResolver().update(TBL_Content.URI, values, selection, selectionArgs);
				
	}
	
	private void startVideo(String videoID){
		Intent intent=YouTubeStandalonePlayer.createVideoIntent(this,Config.YOUTUBE_KEY, videoID,0,true,false);
		startActivityForResult(intent, REQ_START_STANDALONE_PLAYER);
	}
	
	private boolean canResolveIntent(Intent intent) {
	    List<ResolveInfo> resolveInfo = getPackageManager().queryIntentActivities(intent, 0);
	    return resolveInfo != null && !resolveInfo.isEmpty();
	  }

	  private int parseInt(String text, int defaultValue) {
	    if (!TextUtils.isEmpty(text)) {
	      try {
	        return Integer.parseInt(text);
	      } catch (NumberFormatException e) {
	        // fall through
	      }
	    }
	    return defaultValue;
	  }
	  
	  @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
//		  if (requestCode == REQ_START_STANDALONE_PLAYER && resultCode != RESULT_OK) {
//		      YouTubeInitializationResult errorReason =
//		          YouTubeStandalonePlayer.getReturnedInitializationResult(data);
//		      if (errorReason.isUserRecoverableError()) {
//		        errorReason.getErrorDialog(this, 0).show();
//		      } else {
////		        String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
////		        Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
//		      }
//		    }
	}
	
	public static class MyViewPagerAdapter extends FragmentPagerAdapter{
		public int PAGES[]=new int[]{PAGE_VIDEO,PAGE_VIDEO_HISTORY,PAGE_APP};
		private OnVideoItemClickListener mVideoItemClickListener;
		private OnAppItemClickListener mOnAppItemClickListener;
		
		public MyViewPagerAdapter(FragmentManager fm,OnVideoItemClickListener videoItemClickListener,OnAppItemClickListener onAppItemClickListener) {
			super(fm);
			mVideoItemClickListener=videoItemClickListener;
			mOnAppItemClickListener=onAppItemClickListener;
		}

		@Override
		public Fragment getItem(int position) {
			int id=(int) getItemId(position);
			MyListAdapter fragment=null;
			switch (id) {
			case PAGE_VIDEO:
				fragment=MyListAdapter.newInstance(PAGE_VIDEO);
				break;
			case PAGE_VIDEO_HISTORY:
				fragment=MyListAdapter.newInstance(PAGE_VIDEO_HISTORY);
				break;
			case PAGE_APP:
				fragment=MyListAdapter.newInstance(PAGE_APP);
				break;

			default:
				break;
			}
			if(fragment!=null)fragment.setEventClickListener(mVideoItemClickListener, mOnAppItemClickListener);
			
			return fragment;
		}
		@Override
		public long getItemId(int position) {
			return PAGES[position];
		}

		@Override
		public CharSequence getPageTitle(int position) {
			int id=(int) getItemId(position);
			String title="";
			switch (id) {
			case PAGE_VIDEO:
				title=TABS[0];
				break;
			case PAGE_VIDEO_HISTORY:
				title=TABS[1];
				break;
			case PAGE_APP:
				title=TABS[2];
				break;

			default:
				break;
			}
			return title;
		}
		@Override
		public int getCount() {
			return PAGES.length;
		} 
		
	}
	
	public static class MyListAdapter extends Fragment implements LoaderCallbacks<Cursor>{
		
		public static final String EXTRA_TYPE="extra_type";
		
		private int mType;
		private ListView mListView;
		private MyCursorAdapter mCursorAdapter;
		
		private OnVideoItemClickListener mVideoItemClickListener;
		private OnAppItemClickListener mOnAppItemClickListener;
		
		public static MyListAdapter newInstance(int type){
			MyListAdapter myListAdapter=new MyListAdapter();
			Bundle bundle=new Bundle();
			bundle.putInt(EXTRA_TYPE, type);
			myListAdapter.setArguments(bundle);
			return myListAdapter;
		}
		
		public void setEventClickListener(OnVideoItemClickListener videoItemClickListener,OnAppItemClickListener onAppItemClickListener){
			mVideoItemClickListener=videoItemClickListener;
			mOnAppItemClickListener=onAppItemClickListener;
		}
		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			mType=getArguments().getInt(EXTRA_TYPE);
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View view=inflater.inflate(R.layout.fragment_listvideo, container, false);
			initView(view);
			setData();
			return view;
		}
		
		private void initView(View view){
			mListView=(ListView)view.findViewById(R.id.item_list_video);
			mListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> adapter, View arg1,int position, long arg3) {
					Cursor cursor=(Cursor) ((MyCursorAdapter)adapter.getAdapter()).getItem(position);
					
				if(mType==PAGE_APP){
					String url=cursor.getString(cursor.getColumnIndex(TBL_App.URL));
					mOnAppItemClickListener.onAppItemClick(url);
				}else{
					String videoID=cursor.getString(cursor.getColumnIndex(TBL_Content.VIDEO_ID));
					videoID="DRakAPD4fe4";
					if(mVideoItemClickListener!=null)
						mVideoItemClickListener.onVideoItemClick(videoID);
					else Toast.makeText(getActivity(), "null", Toast.LENGTH_LONG).show();
					
					Intent intent=YouTubeStandalonePlayer.createVideoIntent(getActivity(),Config.YOUTUBE_KEY, videoID,0,true,false);
					startActivityForResult(intent, REQ_START_STANDALONE_PLAYER);
					
					//tickwatched
					String selection=TBL_Content.VIDEO_ID+"=?";
					String[] selectionArgs=new String[]{videoID};
					ContentValues values=new ContentValues();
					values.put(TBL_Content.IS_WATCH, 1);
					getActivity().getContentResolver().update(TBL_Content.URI, values, selection, selectionArgs);
				}
				}
			});
		}
		private void setData(){
			mCursorAdapter=new MyCursorAdapter(getActivity(), null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER, mType);
			mListView.setAdapter(mCursorAdapter);
			getLoaderManager().initLoader(mType, null, this);
		}
		
		@Override
		public void onSaveInstanceState(Bundle outState) {
			super.onSaveInstanceState(outState);
//			outState.putParcelable("dd", mVideoItemClickListener);
		}
		@Override
		public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
			//lay' id lam tham so type luon
			String selection="";
			String[] selectionArgs;
			CursorLoader cursorLoader = null;
			switch (id) {
			case PAGE_APP:
				cursorLoader=new CursorLoader(getActivity(), TBL_App.URI, null, null, null, null);
				break;
			case PAGE_VIDEO_HISTORY:
				selection=TBL_Content.IS_WATCH+"=?";
				selectionArgs=new String[]{"1"};
				cursorLoader=new CursorLoader(getActivity(), TBL_Content.URI, null, selection, selectionArgs, null);
				break;
			case PAGE_VIDEO:
				selection=TBL_Content.IS_WATCH+"=?";
				selectionArgs=new String[]{"0"};
				cursorLoader=new CursorLoader(getActivity(), TBL_Content.URI, null, selection, selectionArgs, null);
				break;
			default:
				break;
			}
			return cursorLoader;
		}
		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
			mCursorAdapter.swapCursor(cursor);
		}
		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {
			mCursorAdapter.swapCursor(null);
		}
	}
	
	public static class MyCursorAdapter extends CursorAdapter{

		private int mType;
		
		public MyCursorAdapter(Context context, Cursor c, int flags,int type) {
			super(context, c, flags);
			mType=type;
		}

		@Override
		public void bindView(View arg0, Context arg1, Cursor cursor) {
			if(mType==PAGE_APP){
				TextView txtName=(TextView)arg0.findViewById(R.id.item_list_app_txt_name);
				ImageView imgThumbnail=(ImageView)arg0.findViewById(R.id.item_list_app_img_thumbnail);
				Button btnInstall=(Button)arg0.findViewById(R.id.item_list_app_btn_install);
				
				txtName.setText(cursor.getString(cursor.getColumnIndex(TBL_App.NAME)));
				String imgUrl=cursor.getString(cursor.getColumnIndex(TBL_App.URL));
			}else{
				
				TextView txtName=(TextView)arg0.findViewById(R.id.item_list_video_txt_name);
				ImageView imgThumbnail=(ImageView)arg0.findViewById(R.id.item_list_video_img_thumbnail);
				txtName.setText(cursor.getString(cursor.getColumnIndex(TBL_Content.NAME)));
				String imgUrl=cursor.getString(cursor.getColumnIndex(TBL_Content.THUMBNAIL_URL));
			}
		}

		@Override
		public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
			if(mType==PAGE_APP){
				return View.inflate(arg0, R.layout.item_list_app, null);
			}else{
				return View.inflate(arg0, R.layout.item_list_video, null);
			}
		}
		
	}

}
